jQuery(function($) {
	
	$('.date-picker').datepicker({autoclose:true}).next().on(ace.click_event, function(){
		$(this).prev().focus();
	});

	var dataTable_config = {//jquery_datatable插件的默认参数皮质
	        "bStateSave": true, //是否把获得数据存入cookie
	        //"bLengthChange":false, //关闭每页显示多少条数据
	        "bProcessing": true,
	        "bAutoWidth":false,//自动宽度
	        "bServerSide": true,
	        "sAjaxSource": basePath + "user/getUserList",
	        "fnServerData":retrieveData,
	        "bPaginate": true,  //是否分页。
	        "bFilter": false,
	        "sPaginationType": "bootstrap",      //分页样式
	        "pageLength": 10,
	        "lengthMenu": [
	            [10, 15, 20]// 更改每页显示记录数
	        ],

	        "oLanguage": {//语言设置
				  "sLengthMenu": "每页显示  _MENU_ 条记录",  
				  "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
				  "oPaginate": {
					  "sFirst": "首页",
					  "sPrevious": "前一页",
					  "sNext": "后一页",
					  "sLast": "尾页"
					  },
				  "sZeroRecords": "抱歉， 没有找到",
				  "sInfoEmpty": "没有数据"
				},
				"aoColumns" : [ 
				               {
				            	  "mDataProp" :function ( source, type, val ) {
				            	   /*console.log(source);
				            	   console.log(type);
				            	   console.log(val);*/
				            	   return '<input type="checkbox"  name="checkbox"/>'; 
				               }},
				               { "mDataProp" : "username"},
				               {"mDataProp" : "gender"}, 
				               {"mDataProp" : "age",
				            	   "mRender" :function ( source, type, val ) {
					            	   if(val != null ){
					            		   return source; 
					            	   }else{
					            		   return "";
					            	   }
					               }}, 
				               {"mDataProp" : "userNo",
				            	   "mRender" :function ( source, type, val ) {
					            	   return source; 
					               }}, 
				               {"mDataProp" : "createDt",
				            	   "mRender" :function ( source, type, val ) {
					            	   return source; 
					               }}, 
				               {"mDataProp" : "curState",
				            	   "mRender" :function ( source, type, val ) {
					            	   return source; 
					               }}, 
				               {"mDataProp" : "userId",
			            	     "mRender": function ( source, type, val) {
			                        return ('<button class="btn btn-sm btn-info" onclick="findUser(\''+source+'\');">查看<i class="icon-search  align-top bigger-125 icon-on-right"></i></button>'+
			                        		'&nbsp;&nbsp;<button class="btn btn-sm btn-primary" onclick="editUser(\''+source+'\');">编辑<i class="icon-edit  align-top bigger-125 icon-on-right"></i></button>'+
			                        		'&nbsp;&nbsp;<button class="btn btn-sm btn-danger" onclick="delUser(\''+source+'\');">删除<i class="icon-trash  align-top bigger-125 icon-on-right"></i></button>');
			                    }}
				               
				               ],
				select: {
		            style:    'os',
		            selector: 'td:first-child'
		        },
          
	        "order": [
	            [1, "asc"]
	        ] 
	    };
	var oTable1 = $('#sample-table-2').dataTable(dataTable_config);
	
	function retrieveData( sSource, aoData, fnCallback ) {     
        //查询条件称加入参数数组     
        //var rentRuleId =document.getElementById('rentRuleId').value;  
       //console.log(aoData);
        $.ajax( {  
            type: "POST",
            url: sSource,   
            dataType : 'json',
            data: {
            	"aoData":JSON.stringify(aoData)
            },
            success: function(data) {   
                fnCallback(data); //服务器端返回的对象的returnObject部分是要求的格式
            }     
        });    
    } 
	
	$('table th input:checkbox').on('click' , function(){
		var that = this;
		$(this).closest('table').find('tr > td:first-child input:checkbox')
		.each(function(){
			this.checked = that.checked;
			$(this).closest('tr').toggleClass('selected');
		});
			
	});
	
	
	$('[data-rel="tooltip"]').tooltip({placement: tooltip_placement});
	function tooltip_placement(context, source) {
		var $source = $(source);
		var $parent = $source.closest('table')
		var off1 = $parent.offset();
		var w1 = $parent.width();
	
		var off2 = $source.offset();
		var w2 = $source.width();
	
		if( parseInt(off2.left) < parseInt(off1.left) + parseInt(w1 / 2) ) return 'right';
		return 'left';
	}
	
	$("#bootbox-options").on(ace.click_event, function() {
		bootbox.dialog({
			message: "<span class='bigger-110'>I am a custom dialog with smaller buttons</span>",
			buttons: 			
			{
				"success" :
				 {
					"label" : "<i class='icon-ok'></i> Success!",
					"className" : "btn-sm btn-success",
					"callback": function() {
						//Example.show("great success");
					}
				},
				"danger" :
				{
					"label" : "Danger!",
					"className" : "btn-sm btn-danger",
					"callback": function() {
						//Example.show("uh oh, look out!");
					}
				}, 
				"click" :
				{
					"label" : "Click ME!",
					"className" : "btn-sm btn-primary",
					"callback": function() {
						//Example.show("Primary button");
					}
				}, 
				"button" :
				{
					"label" : "Just a button...",
					"className" : "btn-sm"
				}
			}
		});
	});
	
	$('[data-rel=popover]').popover({container:'body'});
	
});

function rowformater(value,row,index)
{
return "<a href='"+row.id+"' target='_blank'>操作</a>";
}


function addUserModal(){
	$('#myModal').modal('show');
}

function addUser(){
	var user = {};
	var username = $("#add_username").val(); 
	var password = $("#add_password").val();
	var gender = $("input[name='add_gender']:checked").val();
	user.username = username;
	user.password = password;
	user.gender = gender;
	$.ajax( {  
        type: "POST",
        url: basePath + "user/addUser",   
        headers: { 
	        'Accept': 'application/json',
	        'Content-Type': 'application/json' 
	    },
        data: JSON.stringify(user),
        success: function(data) {   
            if(data.returnCode == "SUCCESS"){
            	alert("保存成功");
            	$('#myModal').modal('hide');
            	$("#sample-table-2").dataTable().fnReloadAjax();
            }else{
            	alert("保存失败");
            }
        },
        error:function(data){
        	alert("添加用户出现异常");
        }
    });   
}

function uploadUser(){
	alert("uploadUser");
}

function downloadUser(){
	alert("downloadUser");
}

function findUser(userId){
	$.ajax( {  
        type: "POST",
        url: basePath + "user/findUser",   
	    contentType : "application/x-www-form-urlencoded",
        data: {
        	"userId":userId
        },
        success: function(data) {   
            if(data.returnCode == "SUCCESS"){
            	var user = data.returnMsg;
            	console.log(user);
            	$("#info_username").html(user.username);
            	$("#info_password").html(user.loginPwd);
            	$("#info_gender").html(user.gender);
            	$('#userInfo').modal('show');
            }else{
            	alert("获取用户信息失败");
            }
        },
        error:function(data){
        	alert("获取用户信息，出现异常");
        }
    }); 
}

function editUser(userId){
	$.ajax( {  
        type: "POST",
        url: basePath + "user/findUser",   
	    contentType : "application/x-www-form-urlencoded",
        data: {
        	"userId":userId
        },
        success: function(data) {   
            if(data.returnCode == "SUCCESS"){
            	var user = data.returnMsg;
            	console.log(user);
            	$("#add_username").val(user.username);
            	$("#add_password").val(user.loginPwd);
            	$("input[name='add_gender']:checked").val(user.gender);
            	$('#myModal').modal('show');
            }else{
            	alert("获取用户信息失败");
            }
        },
        error:function(data){
        	alert("获取用户信息，出现异常");
        }
    }); 
}

function delUser(userId){
	bootbox.confirm("确定要删除该用户?", function(result) {
		if(result) {
			$.ajax( {  
		        type: "POST",
		        url: basePath + "user/delUser",   
		        data: {
		        	"userId":userId
		        },
		        success: function(data) {   
		            if(data.returnCode == "SUCCESS"){
		            	alert("删除用户信息成功");
		            	$("#sample-table-2").dataTable().fnReloadAjax();
		            }else{
		            	alert("删除用户信息失败");
		            }
		        },
		        error:function(data){
		        	alert("删除用户信息，出现异常");
		        }
		    }); 
		}else{
			
		}
	});
}

function uploadUser(){
	alert("uploadUser");
}

function downloadUser(){
	alert("downloadUser");
}
